package com.shadow.baiqun.delegate.receive.goodscheck;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.shadow.baiqun.R;
import com.shadow.baiqun.R2;
import com.shadow.baiqun.delegate.common.ResultConverter;
import com.shadow.baiqun.delegate.receive.adapter.CheckAdapter;
import com.shadow.baiqun.delegate.receive.upload.UploadFileDelegate;
import com.shadow.baiqun.event.ModifyPreGoodsEvent;
import com.shadow.baiqun.event.RefreshPreOrderListEvent;
import com.shadow.core.delegate.RxShadowDelegate;
import com.shadow.core.net.callback.IError;
import com.shadow.core.net.callback.ISuccess;
import com.shadow.core.net.rx.RxRestClient;
import com.shadow.core.util.toast.ToastUtils;
import com.shadow.ui.progress.sweetalert.DialogLoader;
import com.shadow.ui.progress.sweetalert.IDialogClickListener;
import com.shadow.ui.recycler.MultipleItemEntity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * @author zy
 * on 2018/5/26
 * 预收货确认
 */
public class CheckDelegate extends RxShadowDelegate {
    private static final String ORDER_ID = "orderId";
    private static final String STATE = "state";

    public static CheckDelegate create(int orderId, int state) {
        final CheckDelegate contentDelegate = new CheckDelegate();
        final Bundle bundle = new Bundle();
        bundle.putInt(ORDER_ID, orderId);
        bundle.putInt(STATE, state);
        contentDelegate.setArguments(bundle);
        return contentDelegate;
    }

    private static final int PAGE_SIZE = 50;
    @BindView(R2.id.toolbar)
    Toolbar mToolbar;
    @BindView(R2.id.recycler_view)
    RecyclerView mRecyclerView;
    CheckAdapter mCheckAdapter;
    private int mPreGoodsOrderId;
    private int mNextRequestPage = 1;
    private boolean isRequesting = false;
    private DialogLoader mDialogLoader;
    //0 可编辑 1只读 2待入库
    private int mState = 0;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mPreGoodsOrderId = bundle.getInt(ORDER_ID);
            mState = bundle.getInt(STATE);
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_check;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pop();
                }
            });
            mToolbar.setTitle("预收货信息核对");
            if (mState == 0) {
                mToolbar.inflateMenu(R.menu.complete);
                mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        int i = item.getItemId();
                        if (i == R.id.menu_complete) {
                            onComplete();
                        }
                        return true;
                    }
                });
            } else if (mState == 2) {
                mToolbar.inflateMenu(R.menu.put);
                mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        int i = item.getItemId();
                        if (i == R.id.menu_put) {
                            put();
                        }
                        return true;
                    }
                });
            }
        }
        EventBus.getDefault().register(this);
        mCheckAdapter = new CheckAdapter(null);
        mCheckAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadMore();
            }
        }, mRecyclerView);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        LinearSnapHelper linearSnapHelper = new LinearSnapHelper();
        linearSnapHelper.attachToRecyclerView(mRecyclerView);
        mCheckAdapter.setEmptyView(R.layout.view_empty, mRecyclerView);
        if (mCheckAdapter.getEmptyView() != null) {
            mCheckAdapter.getEmptyView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    refresh();
                }
            });
        }
        mRecyclerView.setAdapter(mCheckAdapter);
        mDialogLoader = new DialogLoader(getContext());
    }

//    @Override
//    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
//        super.onLazyInitView(savedInstanceState);
//        refresh();
//    }

    @Override
    public void onResume() {
        super.onResume();
        refresh();
    }

    //入库
    public void put() {
        mDialogLoader.showWarning("入库", "已核对完成，确定入库么?",
                new IDialogClickListener() {
                    @Override
                    public void onClick() {
                        mDialogLoader.clearDialog();
                        mDisposables.add(RxRestClient.builder()
                                .loader(getContext())
                                .url("WMS/backstage/collectgoods/sureInDepot")
                                .success(new ISuccess() {
                                    @Override
                                    public void onSuccess(String response) {
                                        if (new ResultConverter().isSucceed(response)) {
                                            ToastUtils.showToast(getContext(), "入库成功");
                                            EventBus.getDefault().post(new RefreshPreOrderListEvent());
                                            startWithPop(UploadFileDelegate.create(mPreGoodsOrderId));
                                        } else {
                                            ToastUtils.showToast(getContext(), "入库失败");
                                        }
                                    }
                                })
                                .error(new IError() {
                                    @Override
                                    public void onError(int code, String msg) {
                                        ToastUtils.showToast(getContext(), "提交失败");
                                    }
                                })
                                .params("pgid", mPreGoodsOrderId)
                                .build()
                                .unRestGet());
                    }
                });

    }

    public void onComplete() {
        mDialogLoader.showWarning("核对完成", "确认所有零件已核对么?"
                , new IDialogClickListener() {
                    @Override
                    public void onClick() {
                        mDialogLoader.clearDialog();
                        mDisposables.add(RxRestClient.builder()
                                .loader(getContext())
                                .url("WMS/backstage/collectgoods/checkCollectGoodsOrder")
                                .success(new ISuccess() {
                                    @Override
                                    public void onSuccess(String response) {
                                        if (new ResultConverter().isSucceed(response)) {
                                            ToastUtils.showToast(getContext(), "提交成功");
                                            EventBus.getDefault().post(new RefreshPreOrderListEvent());
                                            pop();
                                        } else {
                                            JSONObject jsonObject = JSONObject.parseObject(response);
                                            int status = jsonObject.getInteger("status");
                                            if (status == 3) {
                                                //有未填写百群批次的
                                                JSONArray array = jsonObject.getJSONArray("list");
                                                if (array != null) {
                                                    StringBuilder info = new StringBuilder("您还有:");
                                                    for (int i = 0; i < array.size(); i++) {
                                                        String str = (String) array.get(i);
                                                        info.append(str).append("\n");
                                                    }
                                                    info.append("未填写百群批次");
                                                    mDialogLoader.showFailed("提交失败", info.toString(), new IDialogClickListener() {
                                                        @Override
                                                        public void onClick() {
                                                            mDialogLoader.clearDialog();
                                                        }
                                                    });
                                                }
                                            } else {
                                                mDialogLoader.stopProgressWithFailed("提交失败", "");
                                            }
                                        }
                                    }
                                })
                                .error(new IError() {
                                    @Override
                                    public void onError(int code, String msg) {
                                        ToastUtils.showToast(getContext(), "提交失败");
                                    }
                                })
                                .params("flag", 0)
                                .params("pgid", mPreGoodsOrderId)
                                .build()
                                .unRestGet());
                    }
                });

    }

    @Subscribe
    public void onModifiGoodsInfo(final ModifyPreGoodsEvent event) {
        if (isFastClick()) {
            return;
        }
//        mDisposables.add(RxRestClient.builder()
//                .loader(getContext())
//                .url("WMS/backstage/collectgoods/addCollectGoodsPartes")
//                .success(new ISuccess() {
//                    @Override
//                    public void onSuccess(String response) {
//                        if (new ResultConverter().isSucceed(response)) {
//                            ToastUtils.showToast(getContext(), "修改成功!");
//                            mCheckAdapter.notifyItemChanged(event.mPosition);
//                        } else {
//                            ToastUtils.showToast(getContext(), "修改失败!");
//                        }
//                    }
//                })
//                .error(new IError() {
//                    @Override
//                    public void onError(int code, String msg) {
//
//                    }
//                })
//                .params("prepgoodsCPgid", mPreGoodsOrderId)
//                .params("prepgoodsCId", event.mGoodsCheckEntry.getPrepgoodsCId())
//                .params("prepgoodsCCompid", event.mGoodsCheckEntry.getPrepgoodsCCompid())
//                .params("prepgoodsCSupplierid", event.mGoodsCheckEntry.getPrepgoodsCSupplierid())
//                .params("prepgoodsCNum", event.mGoodsCheckEntry.getPrepgoodsCNum())
////                .params("prepgoodsCPgstatus", event.mPartStatus)
//                .build()
//                .unRestGet());
        start(ModifiDelegate.create(event.mGoodsCheckEntry, mPreGoodsOrderId));

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    //刷新
    private void refresh() {
        if (!isRequesting) {
            mNextRequestPage = 1;
            isRequesting = true;
            mCheckAdapter.setEmptyView(R.layout.view_loading, mRecyclerView);
            requestData(true);
        }
    }

    private void requestData(final boolean isRefresh) {
        mDisposables.add(
                RxRestClient.builder()
                        .url("WMS/backstage/collectgoods/getCollectGoodsPartesList")
                        .success(new ISuccess() {
                            @Override
                            public void onSuccess(String response) {
                                mCheckAdapter.setEmptyView(R.layout.view_empty, mRecyclerView);
                                GoodsCheckConverter converter = new GoodsCheckConverter(mState == 0);
                                converter.setJsonData(response);
                                ArrayList<MultipleItemEntity> itemEntities = converter.convert();
                                setData(isRefresh, itemEntities);
                                isRequesting = false;
                            }
                        })
                        .error(new IError() {
                            @Override
                            public void onError(int code, String msg) {
                                mCheckAdapter.setEmptyView(R.layout.view_empty, mRecyclerView);
                                isRequesting = false;
                            }
                        })
                        .params("pgid", mPreGoodsOrderId)
                        .params("page", mNextRequestPage)
                        .params("rows", PAGE_SIZE)
                        .build()
                        .unRestPost());
    }

    private void setData(boolean isRefresh, List<MultipleItemEntity> data) {
        mNextRequestPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            mCheckAdapter.setNewData(data);
        } else {
            if (size > 0) {
                mCheckAdapter.addData(data);
            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            mCheckAdapter.loadMoreEnd(isRefresh);
        } else {
            mCheckAdapter.loadMoreComplete();
        }
    }

    private void loadMore() {
        requestData(false);
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        refresh();
    }
}
